async function queryStudent() {
    const id = document.getElementById("studentId").value;
    const resultDiv = document.getElementById("result");
    resultDiv.innerHTML = "查询中...";

    try {
        const response = await fetch(`/api/student?id=${id}`);
        const data = await response.json();

        if (response.ok) {
            resultDiv.innerHTML = `
            <p>姓名：${data.name}</p>
            <p>性别：${data.gender}</p>
            <p>成绩：${data.score}</p>
            `;
        } else {
            resultDiv.innerHTML = `<p style="color:red;">${data}</p>`;
        }
    } catch (err) {
        resultDiv.innerHTML = `<p style="color:red;">请求失败：${err.message}</p>`;
    }
}

async function addStudent() {
    const id = document.getElementById("newId").value;
    const name = document.getElementById("newName").value;
    const gender = document.getElementById("newGender").value;
    const score = parseInt(document.getElementById("newScore").value, 10);
    const addResult = document.getElementById("addResult");

    try {
        const response = await fetch("/api/add_student", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ id, name, gender, score })
        });
        const data = await response.text();
        if (response.ok) {
            addResult.innerHTML = `<p style="color:green;">${data.message}</p>`;
        } else {
            addResult.innerHTML = `<p style="color:red;">${data}</p>`;
        }
    } catch (err) {
        addResult.innerHTML = `<p style="color:red;">请求失败：${err.message}</p>`;
    }
}

async function loadAllStudents() {
    const tableDiv = document.getElementById("studentTable");
    tableDiv.innerHTML = "加载中...";
  
    try {
      const response = await fetch("/api/all_students");
      const students = await response.json();
  
      if (students.length === 0) {
        tableDiv.innerHTML = `<div class="alert alert-warning">暂无学生数据</div>`;
        return;
      }
  
      let tableHTML = `
        <table class="table table-bordered table-striped">
          <thead>
            <tr>
              <th>学号</th>
              <th>姓名</th>
              <th>性别</th>
              <th>成绩</th>
            </tr>
          </thead>
          <tbody>
      `;
  
      for (const s of students) {
        tableHTML += `
          <tr>
            <td>${s.id}</td>
            <td>${s.name}</td>
            <td>${s.gender}</td>
            <td>${s.score}</td>
          </tr>`;
      }
  
      tableHTML += "</tbody></table>";
      tableDiv.innerHTML = tableHTML;
  
    } catch (err) {
      tableDiv.innerHTML = `<div class="alert alert-danger">加载失败：${err.message}</div>`;
    }
  }
  